package tetris.controller;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyAdapter;
import java.awt.Graphics;
import javax.swing.Timer;
import tetris.model.BoardModel;

public class BoardController extends Controller implements KeyListener{

    private MainController mainController;
    private Timer timer;
    private BoardModel boardModel;
    //public KeyListener kl;
    
    public BoardController(BoardModel m, MainController c){
        this.boardModel = m;
        this.mainController = c;
        timer = new Timer(500, this);
        timer.setActionCommand("step");
        timer.addActionListener(this);
        start();
    }

    public void start(){
        this.boardModel.startBoard();
        this.timer.start();
    }

    private void pauseGame(){
        this.timer.stop();
        this.mainController.backToMenu();
    }

    public void resumeGame(){
        this.timer.start();
    }
    public void paintBoard(Graphics g){
        this.boardModel.paintBoard(g);
    }

    public void actionPerformed(ActionEvent ae){
        if(ae.getActionCommand().equals("step")){
            if(boardModel.isGameOver()){
                this.timer.stop();
                this.boardModel.clearBoard();
                this.view.repaint();
            }else {
                if(this.boardModel.increaseTimer()){
                    this.timer.setDelay(this.timer.getDelay()-50);
                }
                boardModel.step();
                this.view.repaint();
            }
        }
    }

    public void keyTyped(KeyEvent ke) {

    }

    public void keyPressed(KeyEvent ke) {
        if(ke.getKeyCode() == KeyEvent.VK_RIGHT){
            this.boardModel.move(1);
        }else if(ke.getKeyCode() == KeyEvent.VK_LEFT){
            this.boardModel.move(0);
        }else if(ke.getKeyCode() == KeyEvent.VK_SPACE || ke.getKeyCode() == KeyEvent.VK_UP){
            this.boardModel.rotateBlock();
        }else if(ke.getKeyCode() == KeyEvent.VK_DOWN){
            this.boardModel.dropBlock();
        }else if(ke.getKeyCode() == KeyEvent.VK_ESCAPE){
            pauseGame();
        }

        this.view.repaint();
    }

    public void keyReleased(KeyEvent ke) {
        
    }
}
